
var token = window.localStorage.getItem("token");
var pWindow = window.parent;
var sSrc = $('#main-content iframe', pWindow.document).attr('src');
console.log(sSrc);
var projectId = '';
if (sSrc == 'modules/project/projectEnclosure.html') {
    projectId = '000'
}else {
    function getProjectId(src) {
        console.log(src);
        var qs = src.split('?')[1];
        var args = {};
        var items = qs.length ? qs.split('&') : [];
        console.log(items);
        var len = items.length;
        if (qs.length == 0) {
            // alert("没有查询字符串,退出！");
            return;
        }
        for (var i = 0; i < len; i++) {
            var item = items[i].split("=");
            args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
        }
        return args;
    }
    projectId = getProjectId(sSrc).projectId;    // 项目id
}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'generator/projectentity/queryEnclosure/' +projectId,
        datatype: "json",
        colModel: [
			{ label: '项目名称', name: 'projectName', index: 'projectName', width: 80, formatter: function(value, options, row) {
			    console.log(row.enclosurePath);
			    return '<div>' +
                    '<p>' + row.projectName + '</p>' +
                    '<p class="filePath" style="display: none">' + row.enclosurePath + '</p>' +
                    '</div>'
            }},
			{ label: '工作名称', name: 'workName', index: 'workName', width: 80 },
			{ label: '附件名称', name: 'enclosureName', index: 'enclosureName', width: 80 },
			{ label: '上传人', name: 'creationUser', index: 'creationUser', width: 80},
			{ label: '上传时间', name: 'creationTime', index: 'creationTime', width: 80 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });

        }
    });

    $('#task-form').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {/*输入框不同状态，显示图片的样式*/
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {/*验证*/
            taskName: {/*键名username和input name值对应*/
                message: '任务名称校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '任务名不能为空'
                    },
                    stringLength: {
                        max: 60,
                        message: '输入超出长度'
                    }
                }
            },
            durationRequire: {
                message: '工期要求校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '请填写工期要求'
                    }
                }
            },
            phase: {
                message: '阶段名称校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '请选择阶段'
                    }
                }
            }
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        baseTaskInfo: {},
        durationTypeList: [
            {
                typeCode: 1,
                typeLabel: '固定工期'
            },
            {
                typeCode: 2,
                typeLabel: '每周固定日'
            },
            {
                typeCode: 3,
                typeLabel: '每月固定日'
            }
        ],
        phaseList: [],
        templateList: []
	},
    created: function () {
        // this.getPhase();
        // this.getTemplate();

        // created beforeMount mounted

        var _this = this;

        this.baseTaskInfo.durationType = this.durationTypeList[0].typeCode;
        // this.baseTaskInfo.durationType = this.durationTypeList[0].typeCode;

        $.get(baseURL+'generator/basephaseinfo/allList', function (result) {
            console.log(result);
            if (result.code == 0) {
                _this.phaseList = result.list;
                _this.baseTaskInfo.phaseId = _this.phaseList[0].id;
            } else {
                alert(result.msg);
            }
        });


        $.get(baseURL+'generator/basetemplate/query', function (result) {
            console.log(result);
            if (result.code == 0) {
                _this.templateList = result.list;
                _this.baseTaskInfo.templateId = _this.templateList[0].id;
            } else {
                alert(result.msg);
            }
        });
    },
	methods: {
        getPhase: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "generator/basephaseinfo/allList",
                contentType: "application/json",
                success: function(r){
                    console.log(r);
                    if(r.code == 0){
                        vm.phaseList = r.list;
                        // console.log(r.list);
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        getTemplate: function () {
            $.get(baseURL+'generator/basetemplate/query', function (result) {
                console.log(result);
                if (result.code == 0) {
                    vm.templateList = result.list;
                } else {
                    alert(r.msg);
                }
            })
        },
        show: function () {
            if (!this.showList) {

                console.log(!this.showList);
            }
            return !this.showList;
        },
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.baseTaskInfo = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id);
		},
		saveOrUpdate: function (event) {
            var bootstrapValidator = $("#task-form").data('bootstrapValidator');
            bootstrapValidator.validate();
            console.log(bootstrapValidator.isValid());
            if(!bootstrapValidator.isValid()) {
                console.log('验证不通过');
                alert('请输入合法值');
                return false;
            } else {
                console.log(vm.baseTaskInfo.id);
                var url = vm.baseTaskInfo.id == null ? "generator/basetaskinfo/save" : "generator/basetaskinfo/updateTaskInfo";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.baseTaskInfo),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "generator/basetaskinfo/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
            console.log(id);
			$.get(baseURL + "generator/basetaskinfo/queryObjectInfo/"+id,{token:token}, function(r){
			    console.log(r);
                vm.baseTaskInfo = r.baseTaskInfo;
                console.log(r.baseTaskInfo);
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		showValue:function () {

            $('#durationType').on('click',function(){
                var oBtn = $(this);
                $('#ul-durationType').on('click', 'li', function () {
                    var oLi = $(this);
                    oBtn.text(oLi.text());
                    console.log(oLi.text());
                    $('#inp-durationType').val(oLi.text());
                })
            });
        },
        download:function () {
            $.ajax({
                type: "POST",
                url: baseURL + "generator/projectentity/downloadFile",
                headers: {'token': token},
                contentType: "application/json",
                data: JSON.stringify(projectId),
                success: function (r) {
                    console.log(r.imageUrl);
                    if (r.code == 0) {
                        window.location.href=r.imageUrl;
                        alert('操作成功');
                    } else {
                        alert(r.msg);
                    }
                }
            });
        }
	}
});